#!/usr/bin/env python

import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

from django.utils import simplejson

from model import Question
from model import QuestionAnswer


class MyHandler(webapp.RequestHandler):
    
    def get(self):
        question = Question.get(self.request.get('questionKey'))
        if not question:
            self.response.out.write("invalid question key")
            return

        answer = self.request.get('answer')

        if not answer in question.answers:
            self.response.out.write("invalid answer to this question")
            return

        
        if self.request.get('userID') == '' or int(self.request.get('userID')) == 0:
            self.response.out.write("invalid user id")
            return

        userID = int(self.request.get('userID'))

        questionAnswer = None
        existinganswers = db.Query(QuestionAnswer).filter('userID =', userID).filter('question =', question)
        if existinganswers.count() > 0:
            questionAnswer = existinganswers[0]
        else:
            questionAnswer = QuestionAnswer(question = question, userID = userID)

        questionAnswer.answer = answer
        questionAnswer.put()

        self.response.out.write("success")
              
def main():
    app = webapp.WSGIApplication([
        (r'.*', MyHandler)], debug=True)
    wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
    main()